<template>
  <div v-loading="loading">
    <el-form ref="form" :model="form" :rules="rules" label-width="120px" class="dataForm">
      <el-row>
        <el-col :span="12">
          <el-form-item :label="$t('编码')" prop="code">
            <el-input v-model="form.code" :placeholder="$t('编码')" :disabled="form.id" show-word-limit maxlength="100" @change="codeChange" />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item :label="$t('中文')" prop="zhCn">
            <el-input v-model="form.zhCn" :placeholder="$t('中文')" show-word-limit maxlength="100" @change="translation" />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item :label="$t('英文')" prop="enUs">
            <el-input v-model="form.enUs" :placeholder="$t('英文')" show-word-limit maxlength="2000" />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item :label="$t('繁体')" prop="zhTw">
            <el-input v-model="form.zhTw" :placeholder="$t('繁体')" show-word-limit maxlength="100" />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item :label="$t('日文')" prop="jaJp">
            <el-input v-model="form.jaJp" :placeholder="$t('日文')" show-word-limit maxlength="100" />
          </el-form-item>
        </el-col>
      </el-row>
    </el-form>
    <div slot="footer" class="dialog-footer" style="text-align: right;">
      <!--保存，保存并启动流程，取消 三个按钮-->
      <el-button @click="cancel">{{ $t("取消") }}</el-button>
      <el-button v-hasPermi="['system:language:save']" type="primary" @click="submitForm">{{ $t("保存") }}</el-button>
    </div>
  </div>
</template>

<script>
    import { saveSysLanguage, getSysLanguage, getByCode } from '@/api/dev/language/sysLanguage'
    import MD5 from '@/api/md5'
    import axios from 'axios'
    export default {
        data() {
          var validateCode = (rule, value, callback) => {
            if (value && !this.form.id) {
              getByCode(value).then(response => {
                if (response.data) {
                  callback(new Error('该编码已存在'))
                } else {
                  callback()
                }
              })
            } else if (!value) {
              callback(new Error('编码不能为空'))
            } else {
              callback()
            }
          }
          return {
              // 表单参数
              form: {},
              // 遮罩层
              loading: false,
              // 表单校验
              rules: {
                code: { required: true, validator: validateCode, trigger: 'blur' },
                zhCn: { required: true, message: this.$t('必填信息'), trigger: 'blur' }
                // enUs: { required: true, message: this.$t('必填信息'), trigger: 'blur' }
              },
            // 请求百度翻译参数
            translationParams: {
              q: '',
              from: 'zh',
              to: 'en',
              appid: '20201127000627254',
              salt: '12345',
              key: 'uEaHcpntHBYsTjPTAe7u',
              domain: 'finance',
              sign: ''
            }
          }
        },
        computed: {
          disabled() {
            if (this.form.id) {
              return true
            } else {
              return false
            }
          }
        },
        methods: {
            // 初始化数据
            init(data) {
                if (data != null && data.id !== undefined) {
                    getSysLanguage(data.id).then(response => {
                        this.form = response.data
                    })
                } else {
                    this.reset()
                }
            },
            // 表单重置
            reset() {
                this.form = {
                id: undefined,
                code: undefined,
                zhCn: undefined,
                enUs: undefined,
                zhTw: undefined,
                jaJp: undefined,
                createBy: undefined,
                createTime: undefined,
                updateBy: undefined,
                updateTime: undefined
                }
                this.resetForm('form')
            },
            // 取消按钮
            cancel() {
                this.$parent.$parent.formOpen = false
            },
            // 关闭form页面
            closeForm() {
                // 关闭form页面遮罩层
                this.loading = false
                // 关闭form页面
                // this.$parent.$parent.formOpen = false
                this.reset()
                // 刷新list页面
                this.$parent.$parent.getList()
            },
            /** 提交按钮 */
            submitForm: function() {
                this.$refs['form'].validate(valid => {
                    if (valid) {
                        this.loading = true
                        if (this.$i18n.vm.locale === 'zh_cn') {
                          this.$i18n.vm.messages.zh_cn[this.form.code] = this.form.zhCn
                        } else if (this.$i18n.vm.locale === 'en_us') {
                          this.$i18n.vm.messages.en_us[this.form.code] = this.form.enUs
                        } else if (this.$i18n.vm.locale === 'zh_tw') {
                          this.$i18n.vm.messages.zh_tw[this.form.code] = this.form.zhTw
                        } else if (this.$i18n.vm.locale === 'ja_jp') {
                          this.$i18n.vm.messages.ja_jp[this.form.code] = this.form.jaJp
                        }
                        this.updateLocalStorage()
                        saveSysLanguage(this.form).then(response => {
                            if (response.code === 200) {
                                this.msgSuccess(this.$t('保存成功'))
                                this.closeForm()
                            } else {
                                this.msgError(response.msg)
                            }
                            this.loading = false
                        })
                    } else {
                      this.locationError(document)
                    }
                })
           },
          // 修改LocalStorage中的国际化参数
          updateLocalStorage() {
            var zhCn = window.localStorage.getItem('language_zh_cn')
            var enUs = window.localStorage.getItem('language_en_us')
            var zhTw = window.localStorage.getItem('language_zh_tw')
            var jaJp = window.localStorage.getItem('language_ja_jp')

            var zjCnJson = (zhCn !== undefined && zhCn !== null) ? JSON.parse(zhCn) : {}
            var enUsJson = (enUs !== undefined && enUs !== null) ? JSON.parse(enUs) : {}
            var zhTwJson = (zhTw !== undefined && zhTw !== null) ? JSON.parse(zhTw) : {}
            var jaJpJson = (jaJp !== undefined && jaJp !== null) ? JSON.parse(jaJp) : {}
            zjCnJson[this.form.code] = this.form.zhCn
            enUsJson[this.form.code] = this.form.enUs
            zhTwJson[this.form.code] = this.form.zhTw
            jaJpJson[this.form.code] = this.form.jaJp

            window.localStorage.setItem('language_zh_cn', JSON.stringify(zjCnJson))
            window.localStorage.setItem('language_en_us', JSON.stringify(enUsJson))
            window.localStorage.setItem('language_zh_tw', JSON.stringify(zhTwJson))
            window.localStorage.setItem('language_ja_jp', JSON.stringify(jaJpJson))
          },
          translation(val) {
              this.loading = true
              this.translationParams.q = val
              this.translationParams.sign = MD5(this.translationParams.appid + this.translationParams.q + this.translationParams.salt + this.translationParams.domain + this.translationParams.key)
              axios({
                  method: 'get',
                  url: '/api/trans/vip/fieldtranslate?' +
                    'q=' + this.translationParams.q +
                    '&from=' + this.translationParams.from +
                    '&to=' + this.translationParams.to +
                    '&appid=' + this.translationParams.appid +
                    '&salt=' + this.translationParams.salt +
                    '&domain=' + this.translationParams.domain +
                    '&sign=' + this.translationParams.sign
                }).then(res => {
                  this.form.enUs = res.data.trans_result[0].dst.replace(/( |^)[a-z]/g, (L) => L.toUpperCase())
                })
            const sign = MD5(this.translationParams.appid + this.translationParams.q + this.translationParams.salt + this.translationParams.key)
            axios({
                method: 'get',
                url: '/api/trans/vip/translate?' +
                  'q=' + this.translationParams.q +
                  '&from=' + this.translationParams.from +
                  '&to=cht' +
                  '&appid=' + this.translationParams.appid +
                  '&salt=' + this.translationParams.salt +
                  '&sign=' + sign
              }).then(res => {
                this.form.zhTw = res.data.trans_result[0].dst
              })
              axios({
                method: 'get',
                url: '/api/trans/vip/translate?' +
                  'q=' + this.translationParams.q +
                  '&from=' + this.translationParams.from +
                  '&to=jp' +
                  '&appid=' + this.translationParams.appid +
                  '&salt=' + this.translationParams.salt +
                  '&sign=' + sign
              }).then(res => {
                this.loading = false
                this.form.jaJp = res.data.trans_result[0].dst
              })
          },
          codeChange(val) {
              this.form.zhCn = val
              this.translation(val)
          }
        }
    }
</script>
